package com.boronstream.istar;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.boronstream.istar.S.IItemTabMonth;
import com.boronstream.istar.http.PlayNetworkCenter;
import com.boronstream.istar.http.PlayRequestListener;
import com.boronstream.istar.http.PlayResponse;
import com.boronstream.istar.http.request.HoroscopeRequest;
import com.boronstream.istar.http.response.HoroscopeResponse;
import com.boronstream.istar.model.Horoscope;
import com.boronstream.istar.utils.CommonDefine.IntentAction;
import com.boronstream.istar.utils.HelperUtils;
import com.boronstream.istar.utils.Logger;

public interface FragmentMonth {
	public static class MonthFragment extends Fragment implements
			PlayRequestListener {
		private static final String TAG = MonthFragment.class.getSimpleName();

		private IItemTabMonth self;

		private String starName;

		private Horoscope horoscope;

		private IntentFilter filter = new IntentFilter(
				IntentAction.ACTION_STAR_FILTER_CHANGE);
		private MyReceiver receiver = new MyReceiver();

		public MonthFragment() {
			Logger.d(TAG, "new Instance.");
		}

		public static MonthFragment newInstance() {
			MonthFragment fragment = new MonthFragment();
			// Supply num input as an argument.
			Bundle args = new Bundle();
			args.putInt("num", 0);
			fragment.setArguments(args);
			return fragment;
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			Logger.i(TAG, "onActivityCreated");
		}

		@Override
		public void onAttach(Activity activity) {
			Logger.i(TAG, "onAttach");
			super.onAttach(activity);
			try {
				getActivity().registerReceiver(receiver, filter);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onDetach() {
			Logger.i(TAG, "onDetach");
			super.onDetach();
			try {
				getActivity().unregisterReceiver(receiver);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onResume() {
			super.onResume();
			Logger.i(TAG, "onResume");
		}

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			Logger.i(TAG, "onCreate");
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View conView = inflater.inflate(
					com.boronstream.istar.R.layout.i_item_tab_month, container,
					false);
			self = new S.IItemTabMonth(conView);
			horoscope = HelperUtils.getInstance().getHoroscope(getActivity(),
					"h_month");
			this.startGetTodayFortune();
			Logger.w(TAG, "onCreateView:" + self + "," + conView);
			return conView;
		}

		private synchronized void startGetTodayFortune() {
			try {
				SharedPreferences sp = getActivity().getSharedPreferences(
						getString(R.string.app_name), Context.MODE_PRIVATE);
				starName = sp.getString("default_star",
						getString(R.string.default_star));
				Logger.e(TAG, starName + ",horoscope:" + horoscope);
				if (horoscope != null && starName != null
						&& starName.equals(horoscope.getStar_name())) {
					try {
						SimpleDateFormat format = new SimpleDateFormat(
								"yyyy年MM月");
						String dateString = format.format(new Date(System.currentTimeMillis()));
						Logger.d(TAG, "dateString:" + dateString
								+ " updateTime:" + horoscope.getUpdate_time());
						if (dateString.equals(horoscope.getUpdate_time())) {
							this.refreshView(horoscope);
							return;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				HoroscopeRequest request = new HoroscopeRequest();
				request.setStarName(starName);
				request.getRequestParams().put("type", "month");
				PlayNetworkCenter.getInstance().startRequest(request, this);
				self.mProgressBar.setVisibility(View.VISIBLE);
				self.mContentLayout.setVisibility(View.INVISIBLE);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public void setStarName(String starName) {
			this.starName = starName;
		}

		@Override
		public void onRequestFinished(ResultType resultType,
				PlayResponse response) {
			Logger.i(TAG, "resultType:" + resultType.nativeString);
			self.mProgressBar.setVisibility(View.GONE);

			if (response != null && response instanceof HoroscopeResponse) {
				HoroscopeResponse hrscp = (HoroscopeResponse) response;
				horoscope = hrscp.getHoroscope();
				HelperUtils.getInstance().saveHoroscope(getActivity(),
						horoscope, "h_month");
				Logger.i(TAG, horoscope != null ? horoscope.toString() : "");
			}
			this.refreshView(horoscope);
		}

		public void setHoroscope(Horoscope horoscope) {
			this.horoscope = horoscope;
		}

		private void refreshView(Horoscope horoscope) {
			if (horoscope != null) {
				try {
					self.mContentLayout.setVisibility(View.VISIBLE);
					self.mProgressBar.setVisibility(View.GONE);
					self.mTitle.setText(horoscope.getStar_name() + ""
							+ horoscope.getUpdate_time() + "运势");
					
				    self.mTvOverviewDesc.setText(horoscope.getOverview_desc());
				    self.mTvHealthDesc.setText(horoscope.getHealth_desc());
				    self.mTvLoveDesc.setText(horoscope.getLove_desc());
				    self.mTvWealthDesc.setText(horoscope.getWealth_desc());
				    self.mTvWorkDesc.setText(horoscope.getWork_desc());
				    self.mTvNoData.setVisibility(View.GONE);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else {
				self.mTvNoData.setVisibility(View.VISIBLE);
				self.mContentLayout.setVisibility(View.GONE);
				self.mProgressBar.setVisibility(View.GONE);
				self.mTvNoData.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						self.mTvNoData.setVisibility(View.GONE);
						startGetTodayFortune();
					}
				});
			}
		}

		private class MyReceiver extends BroadcastReceiver {

			@Override
			public void onReceive(Context context, Intent intent) {
				if (intent != null
						&& IntentAction.ACTION_STAR_FILTER_CHANGE.equals(intent
								.getAction())) {
					startGetTodayFortune();
				}
			}
		}
	}
}
